<?php

namespace App\Service;

use GuzzleHttp\Client;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Di\Annotation\Inject;

class FootballArticleService
{
    /**
     * @Inject
     * @var ValidatorFactoryInterface
     */
    protected $validatorFactory;

    protected $apiKey = 'sk-14d324c658e64314856bd23c19024ee4';

    protected $webPromptMap = [
        'ifootballkit' => 'footballPrompt'
    ];

    public function generateArticle(array $data): array
    {
        $promptMethod = $this->webPromptMap[$data['webname']] ?? null;
        if (!$promptMethod || !method_exists($this, $promptMethod)) {
            throw new \InvalidArgumentException('不支持该网站的prompt生成');
        }

        $prompt = $this->{$promptMethod}($data);

        $client = new Client([
            'base_uri' => 'https://api.deepseek.com',
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ],
            'verify' => false, // 生产环境建议配置正确的证书
            'timeout' => 80, // 总超时时间60秒
            'connect_timeout' => 10, // 连接超时10秒
            'http_errors' => false // 不抛出HTTP错误异常
        ]);

        try {
            $response = $client->post('/chat/completions', [
                'json' => [
                    'model' => 'deepseek-chat',
                    'messages' => [
                        ['role' => 'system', 'content' => 'You are an expert SEO content writer.'],
                        ['role' => 'user', 'content' => $prompt]
                    ],
                    'stream' => false,
                    'max_tokens' => 3000 // 限制最大token数
                ],
                'timeout' => 80 // 单独请求超时55秒
            ]);


            $result = json_decode($response->getBody()->getContents(), true);

            if (!isset($result['choices'][0]['message']['content'])) {
                throw new \RuntimeException('API返回结构无效');
            }

            $rawContent = $result['choices'][0]['message']['content'];
            $cleanedContent = preg_replace('/^```json|```$/m', '', $rawContent);
            $contentData = json_decode(trim($cleanedContent), true);

            return $contentData;
        } catch (\Exception $e) {
            throw new \RuntimeException('API请求失败: '.$e->getMessage());
        }
    }

    public function validateArticleData(array $data): array
    {
        $validator = $this->validatorFactory->make($data, [
            'name' => 'required|string',
            'description' => 'required|string',
            'meta_title' => 'required|string',
            'meta_description' => 'required|string',
            'tags' => 'required|string',
            'webname' => 'required|string|in:'.implode(',', array_keys($this->webPromptMap)),
            'images' => 'required|string',
            'url' => 'required|string',
        ], [
            'name.required' => '产品名称不能为空',
            'description.required' => '产品描述不能为空',
            'meta_title.required' => 'Meta标题不能为空',
            'meta_description.required' => 'Meta描述不能为空',
            'tags.required' => '标签不能为空',
            'webname.required' => '网站不能为空',
            'webname.in' => '不支持的网站类型',
            'images.required' => '图片不能为空',
            'url.required' => '商品链接不能为空',
        ]);

        if ($validator->fails()) {
            throw new \InvalidArgumentException($validator->errors()->first());
        }

        return $data;
    }

    private function footballPrompt(array $data): string
    {
        return <<<PROMPT
        根据以下商品信息撰写一篇足球服装SEO优化的英文博文：

        Product Name: {$data['name']}
        Description: {$data['description']}
        Meta Tag Title: {$data['meta_title']}
        Meta Tag Description: {$data['meta_description']}
        Product Tags: {$data['tags']}
        Product Images: {$data['images']}

        要求返回JSON格式:
        {
            "post_title": "45–65个字符以内；结合{$data['name']}",
            "short_description": "最多12句话（100160字符）",
            "description": "1000-1400个单词之间；结构清晰（小标题、段落），使用 h2、h3；结合{$data['description']}编写，自然嵌入{$data['keywords']}",
            "meta_tag_title": "50–60字符以内；",
            "meta_tag_description": "120–160字符以内；自然出现关键词"
            "meta_keywords": "根据{$data['name']}撰写5个核心关键词，不要堆砌；与文章内容密切相关"
            "tags": "根据{$data['name']}撰写5个核心关键词"
        }
        PROMPT;
    }
}
